/**
 * 客户端配置管理
 */
const Store = require('electron-store');
const path = require('path');
const os = require('os');
const crypto = require('crypto');

// 加载环境变量
require('dotenv').config({ path: path.join(__dirname, '../../.env') });

class Config {
  constructor() {
    this.store = new Store({
      name: 'file-sync-config',
      defaults: {
        server: {
          host: process.env.SERVER_HOST || 'drive.kbin.cc',
          port: parseInt(process.env.SERVER_PORT) || 3000,
          protocol: process.env.SERVER_PROTOCOL || 'http'
        },
        transfer: {
          maxConcurrent: 3, // 最大并发传输数
          chunkSize: 1024 * 1024, // 1MB分块大小
          autoRetry: true,
          maxRetries: 3
        },
        user: {
          token: null,
          userId: null,
          username: null
        },
        app: {
          autoStart: true,
          autoReconnect: true,
          logLevel: 'info'
        },
        // 🔥 客户端唯一标识
        client: {
          id: null
        }
      }
    });
    
    // 🔥 确保客户端有唯一ID
    this.ensureClientId();
  }
  
  /**
   * 🔥 确保客户端有唯一ID
   */
  ensureClientId() {
    let clientId = this.store.get('client.id');
    if (!clientId) {
      // 生成基于机器信息的唯一ID
      const machineId = crypto.createHash('md5')
        .update(os.hostname() + os.platform() + os.arch())
        .digest('hex');
      clientId = `client_${machineId}_${Date.now()}`;
      this.store.set('client.id', clientId);
      console.log('🆔 生成新的客户端ID:', clientId);
    }
    return clientId;
  }
  
  /**
   * 🔥 获取客户端ID
   */
  getClientId() {
    return this.store.get('client.id');
  }

  // 服务器配置
  getServerConfig() {
    return this.store.get('server');
  }

  setServerConfig(config) {
    this.store.set('server', { ...this.getServerConfig(), ...config });
  }

  getServerUrl() {
    const { protocol, host, port } = this.getServerConfig();
    return `${protocol}://${host}:${port}`;
  }

  getWebSocketUrl() {
    const { host, port } = this.getServerConfig();
    return `ws://${host}:${port}`;
  }

  // 传输配置
  getTransferConfig() {
    return this.store.get('transfer');
  }

  setTransferConfig(config) {
    this.store.set('transfer', { ...this.getTransferConfig(), ...config });
  }

  // 用户配置
  getUserConfig() {
    return this.store.get('user');
  }

  setUserConfig(config) {
    this.store.set('user', { ...this.getUserConfig(), ...config });
  }

  clearUserConfig() {
    this.store.set('user', {
      token: null,
      userId: null,
      username: null
    });
  }

  // 应用配置
  getAppConfig() {
    return this.store.get('app');
  }

  setAppConfig(config) {
    this.store.set('app', { ...this.getAppConfig(), ...config });
  }

  // 检查是否已登录
  isLoggedIn() {
    const user = this.getUserConfig();
    return !!(user.token && user.userId && user.username);
  }

  // 🔥 获取所有配置（用于兼容性）
  get() {
    const serverConfig = this.getServerConfig();
    const userConfig = this.getUserConfig();
    const clientId = this.getClientId();
    
    return {
      serverUrl: this.getServerUrl(),
      token: userConfig.token,
      userId: userConfig.userId,
      username: userConfig.username,
      clientId: clientId,
      server: serverConfig,
      user: userConfig
    };
  }

  // 清除所有配置
  clearAll() {
    this.store.clear();
  }
}

module.exports = new Config();
